//
//  EQSliderItem.swift
//  DSP
//
//  Created by tucici on 2024/5/17.
//

import UIKit
import TCCKit
class EQSliderItem: UICollectionViewCell {
    @IBOutlet var add: UIButton!
    @IBOutlet var sub: UIButton!
    @IBOutlet var valueLbl: UILabel!
    @IBOutlet var bg_slider: UIView!
    @IBOutlet var slider_p: UIImageView!
    @IBOutlet var slider_pY: NSLayoutConstraint!
    @IBOutlet var valueLblTop: NSLayoutConstraint!
    private var maxValue : Float = 20.0
    private var minValue : Float = -20.0
    private var pan2 : UIPanGestureRecognizer!
    var block : (()->Void)?
    override func awakeFromNib() {
        super.awakeFromNib()
        initUI()
    }
    
    func initUI(){
        pan2 = UIPanGestureRecognizer(target:self, action:#selector(actionForPan))
        self.addGestureRecognizer(pan2)
    }
    
    override func setupUI() {
        let value = Float(sign.gain)
        valueLbl.text = String(format: "%0.1f", value < 0 && value > -0.01 ? 0.0 : value)
        let scale = CGFloat(min(value, maxValue)) / CGFloat(maxValue - minValue)
        let offsetY = bg_slider.bounds.height * -scale
        slider_pY.constant = offsetY
    }
    var sign : SignModule = SignModule(){
        didSet{
            pan2.isEnabled = sign.enable
            sign.enable && sign.select ? Tool.labelHightlight(valueLbl) : Tool.labelDisable(valueLbl)
            sign.enable ? Tool.btnNormal(add) : Tool.btnDisable(add)
            sign.enable ? Tool.btnNormal(sub) : Tool.btnDisable(sub)
            setupUI()
        }
    }
    
    @objc private func actionForPan(_ pan:UIPanGestureRecognizer){
        let location = pan.location(in: self)
        var new_y = min(bg_slider.bounds.height, location.y - valueLbl.bounds.height - valueLblTop.constant)
        new_y = max(new_y, 0)
        let y = (bg_slider.bounds.height * 0.5 - new_y) / bg_slider.bounds.height * CGFloat(maxValue - minValue)
        sign.gain = Float(y)
        setupUI()
        NotifyTool.post(updateChartStatus)
        if pan.state == .ended{
            block?()
        }
    }
    
    @IBAction func actionForBtn(_ sender: UIButton) {
        if sign.gain >= maxValue && sender == add {return}
        if sign.gain <= minValue && sender == sub {return}
        let v = sender == add ? sign.gain + 0.1 : sign.gain - 0.1
        sign.gain = Float(v.rounded?(1) ?? 0.0)
        setupUI()
        block?()
    }
    
}
